package com.hm.service.api;


import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.UrlResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
public class PicService1 {


    private final ResourceLoader resourceLoader;

    @Autowired
    public PicService1(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @GetMapping(value = "/image1", produces = MediaType.IMAGE_JPEG_VALUE)
    public ResponseEntity<Resource> getImage(HttpServletRequest request) {
        String name = request.getParameter("name");
        System.out.println("---filename->" + name);

        String token = request.getParameter("token");
        System.out.println("---token->" + token);

        String filePath = "D:/opencv-test/face-pic/";
        Path imageStoragePath = Paths.get(filePath);

        try {
            Path imagePath = imageStoragePath.resolve(name); // 假设图片名为image.jpg
            Resource resource = new UrlResource(imagePath.toUri());
            if (resource.exists() || resource.isReadable()) {
                return ResponseEntity.ok().body(resource);
            } else {
                throw new RuntimeException("Could not read the image: " + imagePath);
            }
        } catch (Exception e) {
            throw new RuntimeException("Error loading image", e);
        }


//
//        try {
//            Path imagePath = imageStoragePath.resolve(filename); // 假设图片名为image.jpg
//            Resource resource = new UrlResource(imagePath.toUri());
//            if (resource.exists() || resource.isReadable()) {
//                return ResponseEntity.ok().body(resource);
//            } else {
//                throw new RuntimeException("Could not read the image: " + imagePath);
//            }
//        } catch (Exception e) {
//            throw new RuntimeException("Error loading image", e);
//        }
    }
}
